<?php

namespace App\Services\Request;

use App\Exceptions\ByteTtsException;
use App\Exceptions\ServiceException;
use App\Logic\Aigc\Exceptions\AigcException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class CallbackRequest extends BaseRequest
{

    /**
     * 接口基础url
     * 若实现了setBaseUri()方法,此处可不定义,两者二选一即可
     * @var string
     */
    public string $baseUri = '';

    //规定的接收成功状态码返回
    const SUCCESS = 'success';

    /**
     * 请求超时时间
     * @var int
     */
    public int $timeout = 60;

    /**
     * 是否开启调试
     * @var bool
     */
    public bool $debug = false;

    public $logTag = 'callback_request';

    public $path = '';


    public function __construct(array $config = [])
    {
        // 解析 URL 中的域名和路径
        $parsedUrl = parse_url($config['url']);
        $domain = ($parsedUrl['scheme'] ?? 'http') . '://' . ($parsedUrl['host'] ?? '');
        $path = $parsedUrl['path'] ?? '';
        $this->baseUri = $domain;
        $this->path = $path;
    }

    /**
     * 设置基础 URI
     * @param string $baseUri 基础 URI
     * @return $this
     */
    public function setBaseUri(): string
    {
        return $this->baseUri;
    }

    public function send(array $params): mixed
    {
        return $this->buildRequest($this->path, $params, 'json');
    }
    /**
     * 重写父类的响应处理,针对不同的三方,则自定义最终响应结果该如何处理
     * @return void
     * @throws \Exception
     */
    public function parseResponse()
    {
        try {
            $content = $this->getContent();
            dd('aaaa',$content);
            if ($content != self::SUCCESS) {
                throw new ServiceException('byte request error');
            }
            return $content;
        } catch (\Throwable $exception) {
            Log::error($this->logTag, [
                'action' => 'byte_tts_request',
                'base_uri' => $this->getBaseUri(),
                'url' => $this->getUri(),
                'params' => $this->getParams(),
                'method' => $this->getMethod(),
                'body' => $this->getBody(),
                'content' => $this->getContent(),
                'message' => $exception->getMessage(),
            ]);
            throw $exception;
        }
    }
}
